import java.io.*;
import java.net.*;

public class ThreadedEchoServer implements Runnable {
	public static final int PORT=7777;
	private Socket sock;
	
	public ThreadedEchoServer(Socket sock) {
		this.sock=sock;
	}
	
	public void run() {
		try {
			
			BufferedReader br=new BufferedReader(
				new InputStreamReader(
						sock.getInputStream(), "UTF-8"));
		
			String richiesta=br.readLine();
			System.out.println("Ricevuta richiesta: "+richiesta);
		
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) { }
			
			System.out.println("Invio la risposta");
			PrintWriter pw=new PrintWriter(
				new OutputStreamWriter(
						sock.getOutputStream(), "UTF-8"));
			pw.print(richiesta);
			pw.println(richiesta);
			pw.flush();
		} catch (IOException exc) {
			System.out.println("Eccezione: "+exc);
		} finally {
			try {
				sock.close();
			} catch (IOException exc2) { }
		}
				
	}
	
	
	public static void main(String args[]) throws IOException {
		ServerSocket ss=new ServerSocket(PORT);
		
		while (true) {
			Socket s=ss.accept();
			ThreadedEchoServer serv=new ThreadedEchoServer(s);
			Thread thread=new Thread(serv);
			thread.start();
		}
	}

}
